//
//  AMapViewController.m
//  Comic
//
//  Created by Ryan on 16/3/21.
//  Copyright © 2016年 程锦. All rights reserved.
//

#import "AMapViewController.h"
#define APIKEY @"7d9a40a80b76d57e5bb797316bf62efe"
#define kDefaultLocationZoomLevel       16.1
#import <MAMapKit/MAMapKit.h>
#import <AMapSearchKit/AMapSearchAPI.h>
#import "AMapSearchKit.h"



@interface AMapViewController ()<MAMapViewDelegate,AMapSearchDelegate,UITableViewDataSource,UITableViewDelegate,UISearchBarDelegate>

{
    
    MAMapView *_mapView;
    
    UIButton *_locationButton;
    
    AMapSearchAPI *_search;
    
    CLLocation *_currentLocation;
    
    UITableView *_tableView;
    
    NSArray *_pois;
    
    NSMutableArray *_annotations;
    
    UISearchBar *_searchBar;
    
    UIView *_navigationView;
    
    UIButton *_backButton;
    
    NSString *_keywords;
    
    UILongPressGestureRecognizer *_longPressGesture;
    
    
   
    MAPointAnnotation *_destinationPoint;
    
    NSArray *_pathPolylines;

    AMapReGeocodeSearchRequest *_pointRequest;
    AMapReGeocodeSearchRequest *_currentRequest;
}



@end

@implementation AMapViewController



- (void)initMapView
{
    
    [MAMapServices sharedServices].apiKey = APIKEY;
    
    _mapView = [[MAMapView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    _mapView.delegate = self;
    
    
    [self.view addSubview:_mapView];
    
    _mapView.showsUserLocation = YES;
    
    _mapView.userTrackingMode = MAUserTrackingModeFollow;
    
    [_mapView setZoomLevel:kDefaultLocationZoomLevel animated:YES];
    
    
}
- (void)initSearch
{
    
    [AMapSearchServices sharedServices].apiKey = APIKEY;
    
    _search = [[AMapSearchAPI alloc]init];
    
    _search.delegate = self;
    
    
    
    
}

- (void)initControls
{
    
    _locationButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _locationButton.frame = CGRectMake(20, CGRectGetHeight(_mapView.bounds) - 80, 40, 40);
    _locationButton.autoresizingMask = UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin;
    _locationButton.backgroundColor = [UIColor whiteColor];
    _locationButton.layer.cornerRadius = 5;
    
    [_locationButton addTarget:self action:@selector(locateAction) forControlEvents:UIControlEventTouchUpInside];
    
    [_locationButton setImage:[UIImage imageNamed:@"location_no"] forState:UIControlStateNormal];
    
    [_mapView addSubview:_locationButton];
    

    
    _navigationView = [[UIView alloc]initWithFrame: CGRectMake(0, 0, SCREEN_WIDTH, 0)];
    
    
    [self.view addSubview:_navigationView];
    
    _navigationView.backgroundColor = [UIColor grayColor];
    
    _searchBar = [UISearchBar new];
    
    _searchBar.placeholder = @"查找地点,公交,地铁";
    
    _searchBar.delegate = self;
    
    _searchBar.showsCancelButton=YES;
    
    [self.view addSubview:_searchBar];
    
    [_searchBar mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.mas_equalTo(10);
        
        make.right.mas_equalTo(-10);
        
        make.top.mas_equalTo(40);
        
        make.height.mas_equalTo(45);
        
        
    }];
    
    
    //
    UIButton *pathButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    pathButton.frame = CGRectMake(80, CGRectGetHeight(_mapView.bounds) - 80, 40, 40);
    pathButton.autoresizingMask = UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin;
    pathButton.backgroundColor = [UIColor whiteColor];
    [pathButton setImage:[UIImage imageNamed:@"path"] forState:UIControlStateNormal];
    pathButton.layer.cornerRadius = 5;

    [pathButton addTarget:self action:@selector(pathAction) forControlEvents:UIControlEventTouchUpInside];
    
    [_mapView addSubview:pathButton];
    
    UIButton *map_Button = [UIButton buttonWithType:UIButtonTypeSystem];
    
    [map_Button addTarget:self action:@selector(mapAction) forControlEvents:UIControlEventTouchUpInside];
    
    [_mapView addSubview:map_Button];
    
    
    
    [map_Button setTitle:@"地图" forState:UIControlStateNormal];
    map_Button.backgroundColor = [UIColor whiteColor];
    map_Button.layer.cornerRadius = 3;
    map_Button.layer.borderWidth = 1;
    map_Button.layer.borderColor = [UIColor grayColor].CGColor;

    
    
    
    
    
    
    UIButton *road_Button = [UIButton buttonWithType:UIButtonTypeSystem];
    
    [road_Button addTarget:self action:@selector(roadAction) forControlEvents:UIControlEventTouchUpInside];
    
    [_mapView addSubview:road_Button];
    
    
    
    [road_Button setTitle:@"路况" forState:UIControlStateNormal];
    road_Button.backgroundColor = [UIColor whiteColor];
    road_Button.layer.cornerRadius = 3;
    road_Button.layer.borderWidth = 1;
    road_Button.layer.borderColor = [UIColor grayColor].CGColor;
    
    
    [map_Button mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.mas_equalTo(_searchBar.mas_bottom).offset(10);
        make.right.mas_equalTo(-10);
        make.width.height.mas_equalTo(40);
        
        
    }];
    
    [road_Button mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.mas_equalTo(map_Button.mas_bottom).offset(10);
        make.right.mas_equalTo(-10);
        make.width.height.mas_equalTo(40);
        
        
        
    }];

    
}


- (void)initAttributes{
    
    _annotations = [NSMutableArray array];
    _pois = nil;
    
}


- (void)initTableView
{
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT, SCREEN_WIDTH, 0) style:UITableViewStylePlain];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    
    [self.view addSubview:_tableView];
}
#pragma mark MAMapViewDelegate
- (void)mapView:(MAMapView *)mapView didLongPressedAtCoordinate:(CLLocationCoordinate2D)coordinate{



        // 添加标注
        if (_destinationPoint != nil)
        {
            // 清理
            [_mapView removeAnnotation:_destinationPoint];
            _destinationPoint = nil;
            
            [_mapView removeOverlays:_pathPolylines];
            _pathPolylines = nil;
        }
        
        _destinationPoint = [[MAPointAnnotation alloc] init];
        _destinationPoint.coordinate = coordinate;
    
    
    _pointRequest = [[AMapReGeocodeSearchRequest alloc] init];
    
    _pointRequest.location = [AMapGeoPoint locationWithLatitude:coordinate.latitude longitude:coordinate.longitude];
    
    [_search AMapReGoecodeSearch:_pointRequest];
    
    
    
    
//        _destinationPoint.title = @"目的地";
//    _destinationPoint.subtitle = @"1111";
        [_mapView addAnnotation:_destinationPoint];
    
    



}
//路线回调
- (MAOverlayView *)mapView:(MAMapView *)mapView viewForOverlay:(id<MAOverlay>)overlay
{
    if ([overlay isKindOfClass:[MAPolyline class]])
    {
        MAPolylineView *polylineView = [[MAPolylineView alloc] initWithPolyline:overlay];
        
        polylineView.lineWidth   = 4;
        polylineView.strokeColor = [UIColor magentaColor];
        
        return polylineView;
    }
    
    return nil;
}


//大头针标注
- (MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id<MAAnnotation>)annotation
{
    
    if (annotation == _destinationPoint)
    {
        static NSString *reuseIndetifier = @"startAnnotationReuseIndetifier";
        MAPinAnnotationView *annotationView = (MAPinAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:reuseIndetifier];
        if (annotationView == nil)
        {
            annotationView = [[MAPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:reuseIndetifier];
        }
        
        annotationView.canShowCallout = YES;
        annotationView.animatesDrop = YES;
        
        return annotationView;
    }
    
    
    
    
    if ([annotation isKindOfClass:[MAPointAnnotation class]])
    {
        static NSString *reuseIndetifier = @"annotationReuseIndetifier";
        MAPinAnnotationView *annotationView = (MAPinAnnotationView*)[mapView dequeueReusableAnnotationViewWithIdentifier:reuseIndetifier];
        if (annotationView == nil)
        {
            annotationView = [[MAPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:reuseIndetifier];
        }
        annotationView.canShowCallout = YES;
        annotationView.animatesDrop = YES;
        
        return annotationView;
    }
    
    return nil;
}


//位置或者设备方向更新后调用此接口
-(void)mapView:(MAMapView *)mapView didUpdateUserLocation:(MAUserLocation *)userLocation
updatingLocation:(BOOL)updatingLocation
{
    if(updatingLocation)
    {
        //取出当前位置的坐标
        //        NSLog(@"latitude : %f,longitude: %f",userLocation.coordinate.latitude,userLocation.coordinate.longitude);
        
        _currentLocation = [userLocation.location copy];
        NSLog(@"latitude : %f,longitude: %f",_currentLocation.coordinate.latitude,_currentLocation.coordinate.longitude);
        
    }
}



- (void)mapView:(MAMapView *)mapView didChangeUserTrackingMode:(MAUserTrackingMode)mode animated:(BOOL)animated
{
    // 修改定位按钮状态
    if (mode == MAUserTrackingModeNone)
    {
        [_locationButton setImage:[UIImage imageNamed:@"location_no"] forState:UIControlStateNormal];
    }
    else
    {
        [_locationButton setImage:[UIImage imageNamed:@"location_yes"] forState:UIControlStateNormal];
    }
}

- (void)mapView:(MAMapView *)mapView didSelectAnnotationView:(MAAnnotationView *)view
{
    // 选中定位annotation的时候进行逆地理编码查询
    if ([view.annotation isKindOfClass:[MAUserLocation class]])
    {
        [self reGeoAction];
    }
}

#pragma mark AMapSearchDelegate
- (void)searchRequest:(id)request didFailWithError:(NSError *)error
{
    NSLog(@"request :%@, error :%@", request, error);
}




- (void)onRouteSearchDone:(AMapRouteSearchBaseRequest *)request response:(AMapRouteSearchResponse *)response{


        NSLog(@"request: %@", request);
        NSLog(@"response: %@", response);
    if (response.count > 0)
    {
        [_mapView removeOverlays:_pathPolylines];
        _pathPolylines = nil;
    
        // 只显示第一条
        _pathPolylines = [self polylinesForPath:response.route.paths[0]];
        [_mapView addOverlays:_pathPolylines];
    
        [_mapView showAnnotations:@[_destinationPoint, _mapView.userLocation] animated:YES];
    }


}




- (void)onPOISearchDone:(AMapPOISearchBaseRequest *)request response:(AMapPOISearchResponse *)response
{
    
    
    if(response.pois.count == 0)
    {
        return;
    }
    

    if (response.pois.count > 0)
    {
        _pois = response.pois;
        
        
        
        [_tableView reloadData];
        
        // 清空标注
        [_mapView removeAnnotations:_annotations];
        [_annotations removeAllObjects];
    }
    
    
}

- (void)onReGeocodeSearchDone:(AMapReGeocodeSearchRequest *)request response:(AMapReGeocodeSearchResponse *)response
{
    NSLog(@"response :%@", response);
    
 
    
    if (request == _currentRequest) {
        NSString *title = response.regeocode.addressComponent.city;
        if (title.length == 0)
        {
            title = response.regeocode.addressComponent.province;
        }
        
        _mapView.userLocation.title = title;
        _mapView.userLocation.subtitle = response.regeocode.formattedAddress;

    }else{
    
        NSString *title = response.regeocode.addressComponent.city;
        if (title.length == 0)
        {
            title = response.regeocode.addressComponent.province;
        }
        _destinationPoint.title = title;
        _destinationPoint.subtitle = response.regeocode.formattedAddress;
        

    }
    
    
}


#pragma mark - UITableViewDataSource

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier = @"cellIdentifier";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    
    if (cell == nil)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIdentifier];
    }
    
    AMapPOI *poi = _pois[indexPath.row];
    
    cell.textLabel.text = poi.name;
    cell.detailTextLabel.text = poi.address;
    
    return cell;
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _pois.count;
}

#pragma mark - UITableViewDelegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    // 为点击的poi点添加标注
    AMapPOI *poi = _pois[indexPath.row];
    
    MAPointAnnotation *annotation = [[MAPointAnnotation alloc] init];
    annotation.coordinate = CLLocationCoordinate2DMake(poi.location.latitude, poi.location.longitude);
    annotation.title = poi.name;
    annotation.subtitle = poi.address;
    
    
    [_annotations addObject:annotation];

    [_mapView addAnnotation:annotation];
    
    
    //设置中心点
    [_mapView setCenterCoordinate:CLLocationCoordinate2DMake(poi.location.latitude, poi.location.longitude) animated:YES];
    
    [self backAction];
    
}

#pragma mark searchBarDelegate




- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar
{
    
    
    
    
    _navigationView.hidden = NO;
    
    _tableView.hidden = NO;
    
    [UIView animateWithDuration:0.5 animations:^{
        
        _navigationView.frame = CGRectMake(0, 0, SCREEN_WIDTH, 85);
        
        _backButton.frame = CGRectMake(5, CGRectGetHeight(_navigationView.bounds)-45, 40, 40);
        
        _tableView.frame = CGRectMake(0, 85, SCREEN_WIDTH, SCREEN_HEIGHT-85);
        
        
    }];
    
    
    _pois = [NSArray array];
    
    
    [_tableView reloadData];
    
    
    
    
}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
    
    
    NSLog(@"%@",searchText);
    
    if (searchText.length > 0) {
        
        _keywords = searchText;
        
        [self searchAction];
        
    }else{
        
        
        _navigationView.hidden = YES;
        
        _tableView.hidden = YES;
        
        [UIView animateWithDuration:0.5 animations:^{
            
            _navigationView.frame = CGRectMake(0, 0, SCREEN_WIDTH, 0);
            
            _backButton.frame = CGRectMake(5, CGRectGetHeight(_navigationView.bounds)-45, 40, 40);
            
            _tableView.frame = CGRectMake(SCREEN_HEIGHT, 85, SCREEN_WIDTH, SCREEN_HEIGHT-85);
            
            
        }];
        
        
        
        [searchBar resignFirstResponder];
        
        _pois = [NSArray array];
        
        [_tableView reloadData];
        
        
    }
    
    
    
}

-(void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
    
    searchBar.text = @"";
    
    
    
    _navigationView.hidden = YES;
    
    _tableView.hidden = YES;
    
    [UIView animateWithDuration:0.5 animations:^{
        
        _navigationView.frame = CGRectMake(0, 0, SCREEN_WIDTH, 0);
        
        _backButton.frame = CGRectMake(5, CGRectGetHeight(_navigationView.bounds)-45, 40, 40);
        
        _tableView.frame = CGRectMake(SCREEN_HEIGHT, 85, SCREEN_WIDTH, SCREEN_HEIGHT-85);
        
        
    }];
    
    [searchBar resignFirstResponder];
    
    _pois = [NSArray array];
    
    [_tableView reloadData];
    
    
    
    
    
    
    
    
}



#pragma mark 点击方法


- (void)mapAction{

    
    if(_mapView.mapType == MAMapTypeSatellite){
        
        _mapView.mapType = MAMapTypeStandard;

      
    }else{
        _mapView.mapType = MAMapTypeSatellite;

        }

}

- (void)roadAction{
    
    _mapView.showTraffic = !_mapView.showTraffic;

}

- (void)locateAction
{
    if (_mapView.userTrackingMode != MAUserTrackingModeFollow)
    {
        [_mapView setUserTrackingMode:MAUserTrackingModeFollow animated:YES];
    }
    
}

- (void)searchAction
{
    if (_currentLocation == nil || _search == nil)
    {
        NSLog(@"search failed");
        return;
    }
    
    //构造AMapPOIAroundSearchRequest对象，设置周边请求参数
    AMapPOIAroundSearchRequest *request = [[AMapPOIAroundSearchRequest alloc] init];
    request.location = [AMapGeoPoint locationWithLatitude:_currentLocation.coordinate.latitude longitude:_currentLocation.coordinate.longitude];
    request.keywords = _keywords;
    // types属性表示限定搜索POI的类别，默认为：餐饮服务|商务住宅|生活服务
    // POI的类型共分为20种大类别，分别为：
    // 汽车服务|汽车销售|汽车维修|摩托车服务|餐饮服务|购物服务|生活服务|体育休闲服务|
    // 医疗保健服务|住宿服务|风景名胜|商务住宅|政府机构及社会团体|科教文化服务|
    // 交通设施服务|金融保险服务|公司企业|道路附属设施|地名地址信息|公共设施
    request.types = @"餐饮服务|生活服务";
    request.sortrule = 0;
    request.requireExtension = YES;
    
    //发起周边搜索
    [_search AMapPOIAroundSearch: request];
    
}

- (void)pathAction
{
    if (_destinationPoint == nil || _currentLocation == nil || _search == nil)
    {
        NSLog(@"path search failed");
        return;
    }
    
    AMapDrivingRouteSearchRequest *request = [[AMapDrivingRouteSearchRequest alloc] init];
    
    // 设置为步行路径规划
//    request.searchType = AMapSearchType_NaviWalking;
    request.strategy = 2;//距离优先
    request.origin = [AMapGeoPoint locationWithLatitude:_currentLocation.coordinate.latitude longitude:_currentLocation.coordinate.longitude];
    request.destination = [AMapGeoPoint locationWithLatitude:_destinationPoint.coordinate.latitude longitude:_destinationPoint.coordinate.longitude];
    
    [_search AMapDrivingRouteSearch:request];
}


- (void)backAction
{
    [_searchBar resignFirstResponder];
    
    _searchBar.text = @"";
    _navigationView.hidden = YES;
    
    _tableView.hidden = YES;
    
    [UIView animateWithDuration:0.5 animations:^{
        
        _navigationView.frame = CGRectMake(0, 0, SCREEN_WIDTH, 0);
        
        _backButton.frame = CGRectMake(5, CGRectGetHeight(_navigationView.bounds)-45, 40, 40);
        
        _tableView.frame = CGRectMake(0, SCREEN_HEIGHT, SCREEN_WIDTH, SCREEN_HEIGHT);
        
        
    }];
}


- (void)reGeoAction
{
    if (_currentLocation)
    {
        _currentRequest = [[AMapReGeocodeSearchRequest alloc] init];
        
        _currentRequest.location = [AMapGeoPoint locationWithLatitude:_currentLocation.coordinate.latitude longitude:_currentLocation.coordinate.longitude];
        
        [_search AMapReGoecodeSearch:_currentRequest];
        
        
    }
    
 
}



- (CLLocationCoordinate2D *)coordinatesForString:(NSString *)string
                                 coordinateCount:(NSUInteger *)coordinateCount
                                      parseToken:(NSString *)token
{
    if (string == nil)
    {
        return NULL;
    }
    
    if (token == nil)
    {
        token = @",";
    }
    
    NSString *str = @"";
    if (![token isEqualToString:@","])
    {
        str = [string stringByReplacingOccurrencesOfString:token withString:@","];
    }
    
    else
    {
        str = [NSString stringWithString:string];
    }
    
    NSArray *components = [str componentsSeparatedByString:@","];
    NSUInteger count = [components count] / 2;
    if (coordinateCount != NULL)
    {
        *coordinateCount = count;
    }
    CLLocationCoordinate2D *coordinates = (CLLocationCoordinate2D*)malloc(count * sizeof(CLLocationCoordinate2D));
    
    for (int i = 0; i < count; i++)
    {
        coordinates[i].longitude = [[components objectAtIndex:2 * i]     doubleValue];
        coordinates[i].latitude  = [[components objectAtIndex:2 * i + 1] doubleValue];
    }
    
    return coordinates;
}


- (NSArray *)polylinesForPath:(AMapPath *)path
{
    if (path == nil || path.steps.count == 0)
    {
        return nil;
    }
    
    NSMutableArray *polylines = [NSMutableArray array];
    
    [path.steps enumerateObjectsUsingBlock:^(AMapStep *step, NSUInteger idx, BOOL *stop) {
        
        NSUInteger count = 0;
        CLLocationCoordinate2D *coordinates = [self coordinatesForString:step.polyline
                                                         coordinateCount:&count
                                                              parseToken:@";"];
        
        MAPolyline *polyline = [MAPolyline polylineWithCoordinates:coordinates count:count];
        [polylines addObject:polyline];
        
        free(coordinates), coordinates = NULL;
    }];
    
    return polylines;
}



- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    
    self.navigationController.navigationBarHidden = YES;
    
    
    
}

- (void)viewDidDisappear:(BOOL)animated{
    
    self.navigationController.navigationBarHidden = NO;
    
}



- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self initMapView];
    [self initControls];
    [self initSearch];
    [self initTableView];
    [self initAttributes];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
